<?php


namespace console\controllers;

use Yii;
use console\models\Settings;

class PublicController extends \yii\console\Controller{
    
    protected $cache;
    protected $redis;
    protected $logPath;


    public function __construct($id, $module, $config = array()) {
        parent::__construct($id, $module, $config);
        $this->getLogPath();
        $this->cache = Yii::$app->cache;
        $this->redis = Yii::$app->redis;
    }

    /**
     * 获得Log目录位置
     */
    private function getLogPath() {
        $this->logPath = $this->setting('log_path');
        if (!file_exists($this->logPath)) {
            @mkdir($this->logPath, 777);
        }
    }

    /**
     * 数据返回方式
     */
    protected function renderJson($data) {
        $type = 'json';
        if (is_array($data)) {
            $type = 'array';
            $data = Json::encode($data);
        }
        die($data);
    }

    /**
     * 获取设置
     */
    protected function setting($key, $field = 'setValue') {
        $cacheKey = 'setting_'.$key;
        $data = unserialize(Yii::$app->redis->get($cacheKey));
        if(empty($data)){
            $data = Settings::find()->where(['setTag' => $key])->asArray()->one();
            if (empty($data)) {
                return false;
            }
            Yii::$app->redis->set($cacheKey, serialize($data));
        }
        return $data[$field];
    }

    /**
     * 产生Log
     */
    protected function setLog($name, $content, $showSystemParam = false) {
        $d = ['time' => date('Y-m-d H:i:s'), 'data' => $content];
        if($showSystemParam){
            $d['sysParam'] = ['post' => Yii::$app->request->post(), 'get' => Yii::$app->request->get(), 'input' => file_get_contents('php://input'), 'serverInfo' => $_SERVER];
        }
        $file = $this->logPath . $name . '.log';
        $line = "\n\n-------------------------------------------------------分割线----------------------------------------------------------\n\n\n";
        $log = print_r($d, 1). $line;
        return @file_put_contents($file, $log, FILE_APPEND);
    }
    
    /**
     * sha1
     */
    protected function sha1($str, $salt = ''){
        if(empty($salt)){
            return sha1($str, false);
        }else{
            return sha1($salt.'_'.$str.'_'.$salt);
        }
    }
    
    /**
     * sha256
     * @param string $baseStr
     * @param string $salt
     * @param bool $rawOutput
     * @return string
     */
    protected function sha256($baseStr, $salt = '', $rawOutput = false){
        if (!is_scalar($baseStr)) {
            return false;
        }
        $cacheKey = 'sha256_'.$baseStr.'_'.$salt;
        $sha256 = $this->redis->get($cacheKey);
        if(empty($sha256)){
            $str = $salt == '' ? $baseStr : $salt.'_'.$baseStr.'_'.$salt;
            $sha256 = hash('sha256', $str, $rawOutput);
            $this->redis->set($cacheKey, $sha256);
        }
        return $sha256;
    }
    
    /**
     * 发送模板消息
     */
    protected function sendTempMsg($tmpId, $data, $url, $openId){
        //获取接口调用Token
        //根据模板编号，组装消息
        //调用接口发出
        $d = ["touser" => $openId, "template_id" => $tmpId, "url" => $url, "data" => $data];
        $listKey = $this->setting('template_message_queque_key');
        return $this->redis->lpush($listKey, serialize($d));
    }
    
    /**
     * 根据配置发送模板消息
     * @param type $configKey
     * @param type $openId
     * @param type $data
     * @return type
     */
    protected function sendTemplateMsg($configKey, $openId, $data){
        if(empty($openId)){return ['result' => false, 'msg' => '通知消息因不知道发送给谁而发送失败'];}
        $config = $this->setting($configKey);
        if(empty($config)){return ['result' => false, 'msg' => '通知消息因发送配置未找到而发送失败'];}
        $configs = explode('|', $this->setting($configKey));
        $templateId = $configs[0];
        $url = $configs[1];
        $varTemp = explode(',', $configs[2]);
        $d = [];
        foreach((array)$varTemp as $v){
            if(!isset($data[$v])){return ['result' => false, 'msg' => '通知消息因消息变量“'.$v.'”未设置而发送失败'];}
            $d[$v] = $data[$v];
        }
        $params = ["touser" => $openId, "template_id" => $templateId, "url" => $url, "data" => $d];
        Yii::$app->wx->sendMessage($params);
        return ['result' => true, 'msg' => '通知发送成功'];
    }
    
    protected function password($password, $passwordKey = ''){
        if($passwordKey == ''){
            $passwordKey = $this->getGuid('pwd_');
        }
        $password = $this->sha256($password, $passwordKey);
        return ['passwordKey' => $passwordKey, 'password' => $password];
    }
}
